var insd = {};

//覆盖方法
function overrideFlowFunctions() {
	
	//是否可以弹出组件菜单
	window.flbpmn_hasContextPad = function(elem) {
		var type = getBpmnType(elem);
		if (!type) return false;
		if ('SequenceFlow'==type) {
			return !insd.seqflows[elem.id];
		} else if (type.indexOf("Task")>=0 || type.indexOf("Gateway")>=0 || type.indexOf("SubProcess")>=0
				||type.indexOf("Event")>=0) {
			var state = id_getState(elem.id);
			return state!='done';
		}
		return true;
	}

	//是否可以移动 elems为数组
	window.flbpmn_canMove = function(elems) {
		/*if (elems && elems.length) {
			for (var i in elems) {
				if (fl.curflow.oldBpmnConfig[elems[i].id]) {
					return false;
				}
			}
			return true;
		}
		return false;*/
		return true;
	}

	//是否可以修改大小
	window.flbpmn_canResize = function(elem) {
		return true;
	}

	//是否可以删除
	window.flbpmn_canDelete = function(elem) {
		var type = getBpmnType(elem);
		if ('SequenceFlow'==type) {
			return !insd.seqflows[elem.id];
		} else if (type.indexOf("Task")>=0 || type.indexOf("Gateway")>=0 || type.indexOf("SubProcess")>=0
				||type.indexOf("Event")>=0) {
			var state = id_getState(elem.id);
			return state=='new' || state=="pending";
		}
		return true;
	}

	//是否可以修改类型
	window.flbpmn_canChangeType = function(elem) {
		var state = id_getState(elem.id);
		return state=='new' || state=='pending';
	}

	//是否可以修改属性
	window.flbpmn_canChangeProps = function(elem) {
		var state = id_getState(elem.id);
		return state=='new' || state=='pending';
	}
	
	//是否可以修改文字
	window.flbpmn_canChangeLabel = function(elem) {
		var state = id_getState(elem.id);
		return state=='new' || state=='pending';
	}
	
	//是否可以修改线中间的点
	window.flbpmn_canConnUpdateWaypoints = function(elem) {
		return !insd.seqflows[elem.id];
	}
	
	//是否可以修改线开始节点
	window.flbpmn_canConnReconnectStart = function(elem) {
		return !insd.seqflows[elem.id];
	}
	
	//是否可以修改线结束节点
	window.flbpmn_canConnReconnectEnd = function(elem) {
		return !insd.seqflows[elem.id];
	}
	
	window.initCanvasToolbar = function() {
		if (!fl.tbcavans) {
			fl.tbcavans = fl.cell_designer.attachToolbar();
		
			//设置按钮栏
			fl.tbcavans.setIconsPath(flvar.iconpath);
			//添加按钮 从右至左
			fl.tbcavans.addButton('btn_close', 0, fmd_i18n_b_close, 'browserClose1.png', 'browserClose1_dis.png');
			fl.tbcavans.addButton('btn_help', 0, fmd_i18n_b_help, 'help1.png', 'help1_dis.png');
			fl.tbcavans.addText('txt_curflow', 0, '');//用于显示当前流程名称
			fl.tbcavans.addSeparator('sp4', 0);//分割线
			
			//fl.tbcavans.addButton('btn_simulate', 0, '', 'simulate.png', 'simulate_dis.png');//play
			//fl.tbcavans.addButton('btn_vertical', 0, '', 'vertical.png', 'vertical_dis.png');//vertical mode
            fl.tbcavans.addButton('btn_downpdf', 0, '', 'downsvg.png', 'downsvg_dis.png');//导出PDF
			fl.tbcavans.addButton('btn_downsvg', 0, '', 'downsvg.png', 'downsvg_dis.png');//导出svg
			fl.tbcavans.addButton('btn_downbpmn', 0, '', 'downbpmn.png', 'downbpmn_dis.png');//导出bpmn
			fl.tbcavans.addSeparator('sp3', 0);
			
			//fl.tbcavans.addButton('btn_settimeline', 0, '', 'time1.png', 'time1_dis.png');
			
			fl.tbcavans.addButton('btn_resetscroll', 0, '', 'relocate1.png', 'relocate1_dis.png');//定位到原点
			fl.tbcavans.addButton('btn_fs1', 0, '', 'fullscreen1.png', 'fullscreen1_dis.png');//全屏
			fl.tbcavans.addButton('btn_fs', 0, '', 'fullscreen.png', 'fullscreen_dis.png');//全屏
			fl.tbcavans.addButton('btn_theme', 0, '', 'theme1.png', 'theme1_dis.png');//修改主题
			fl.tbcavans.addSeparator('sp2', 0);
			
			fl.tbcavans.addButton('btn_showValidate', 0, '', 'showValidation.png', 'showValidation_dis.png');//显示验证消息
			fl.tbcavans.addButton('btn_validate', 0, '', 'validation.png', 'validation_dis.png');//验证
			fl.tbcavans.addSeparator('sp1', 0);
			
			fl.tbcavans.addButton('btn_redo', 0, fmd_i18n_b_redo, 'redo.png', 'redo_dis.png');
			fl.tbcavans.addButton('btn_undo', 0, fmd_i18n_b_undo, 'undo.png', 'undo_dis.png');
			fl.tbcavans.addSeparator('sp0', 0);
			//fl.tbcavans.addButton('btn_renewVertical', 0, '重新生成', 'refresh1.png', 'refresh1_dis.png');
			fl.tbcavans.addButton('btn_reset', 0, fmd_i18n_b_reset, 'revert.png', 'revert_dis.png');
			fl.tbcavans.addButton('btn_save', 0, fmd_i18n_b_save, 'save.png', 'save_dis.png');
			
			fl.tbcavans.setItemToolTip('btn_close', fmd_i18n_b_close);
			fl.tbcavans.setItemToolTip('btn_help', fmd_i18n_b_help);
            fl.tbcavans.setItemToolTip('btn_downpdf', fmd_i18n_b_downpdf);
			fl.tbcavans.setItemToolTip('btn_downsvg', fmd_i18n_b_downsvg);
            fl.tbcavans.setItemToolTip('btn_downbpmn', fmd_i18n_b_downbpmn);
			//fl.tbcavans.setItemToolTip('btn_settimeline', '时间单位设置');
			fl.tbcavans.setItemToolTip('btn_resetscroll', fmd_i18n_b_resetscroll);
			fl.tbcavans.setItemToolTip('btn_theme', fmd_i18n_b_theme);
			fl.tbcavans.setItemToolTip('btn_showValidate', fmd_i18n_b_showValidate);
			fl.tbcavans.setItemToolTip('btn_validate', fmd_i18n_b_validate);
			fl.tbcavans.setItemToolTip('btn_fs', fmd_i18n_b_fs);
			fl.tbcavans.setItemToolTip('btn_fs1', fmd_i18n_b_fs1);
			fl.tbcavans.setItemToolTip('btn_redo', fmd_i18n_b_redo);
			fl.tbcavans.setItemToolTip('btn_undo', fmd_i18n_b_undo);
			fl.tbcavans.setItemToolTip('btn_reset', fmd_i18n_b_reset);
			fl.tbcavans.setItemToolTip('btn_save', fmd_i18n_b_save);
			//fl.tbcavans.setItemToolTip('btn_vertical', fmd_i18n_verticalview);
			//fl.tbcavans.setItemToolTip('btn_simulate', fmd_i18n_simulate);

			fl.tbcavans.addSpacer('txt_curflow');
			
			//按钮栏事件
		    fl.tbcavans.attachEvent('onClick', function(btid) {
		    	if (btid=='btn_downbpmn') {//导出bpmn
		    		bi.saveDiagram(function(err, xml){
		    			downloadFile(fl.curflow.name+".bpmn", xml);
		    		});
		    	} else if (btid=='btn_downsvg') {//导出svg
		    		bi.saveSVG(function(err, xml){
		    			unSelect();
		    			downloadFile(fl.curflow.name+".svg", xml);
		    		});
		    	} else if (btid=='btn_save') {//保存
		    		$("svg text > tspan").show();
		    		validateFlowAndSave(true);
	    			if (fl_getScale() < 0.6) {
		    			$("svg text > tspan").hide();
		    		}
		    	} else if (btid=='btn_validate') {//验证并保存
		    		validateFlowAndSave(false);
		    	} else if (btid=='btn_showValidate') {//显示验证错误
		    		showValidationErrors(false);
		    	} else if (btid=='btn_reset') {//重置
		    		if (fl.unSavedChange) {
		    			dhtmlx.message({
			                "type": "confirm-warning",
			                "title" : fmd_i18n_title_tip,
			    			"text": fmd_i18n_msg_unsavedchange,
			    			"ok" : fmd_i18n_b_yes,
			    			"cancel" : fmd_i18n_b_no,
			    			"callback" : function(y) {if (y) {editFlow(fl.curflow.id);}}
			    		});
		    		} else {
		    			editFlow(fl.curflow.id);
		    		}
		    	} else if (btid=='btn_renewVertical') {//重新生成纵向视图
		    		dhtmlx.message({
		                "type": "confirm-warning",
		                "title" : fmd_i18n_title_tip,
		    			"text": fmd_i18n_msg_renewvertical,
		    			"ok" : fmd_i18n_b_yes,
		    			"cancel" : fmd_i18n_b_no,
		    			"callback" : function(y) {if (y) {fl_renewVertical();}}
		    		});
		    	} else if (btid=='btn_undo') {//撤销
		    		fl_waitstart();
		    		bi.editorActions.undo();
		    		fl_waitend();
		    	} else if (btid=='btn_redo') {//重做
		    		fl_waitstart();
		    		bi.editorActions.redo();
		    		fl_waitend();
		    	} else if (btid=='btn_fs') {//全屏设计区
		    		fullScreenApi.requestFullScreen(document.querySelector('.canvas'));
		    	} else if (btid=='btn_fs1') {//全屏设计器
		    		var el = $('#maindiv > .dhx_cell_layout:last')[0];
		    		if (fullScreenApi.isFullScreen(el)) {
						fullScreenApi.cancelFullScreen(el);
					} else {
						fullScreenApi.requestFullScreen(el);
					}
		    	} else if (btid=='btn_resetscroll') {//定位到原点
		    		fl_resetScroll();
		    	} else if (btid=='btn_close') {//关闭
					//如果是全屏，先关闭全屏
					var el = $('#maindiv > .dhx_cell_layout:last')[0];
					if (fullScreenApi.isFullScreen(el)) {
						fullScreenApi.cancelFullScreen(el);
					} else {
						if (fl.unSavedChange) {
			    			dhtmlx.message({
				                "type": "confirm-warning",
				                "title" : fmd_i18n_title_tip,
				    			"text": fmd_i18n_msg_unsavedchange,
				    			"ok" : fmd_i18n_b_yes,
				    			"cancel" : fmd_i18n_b_no,
				    			"callback" : function(y) {if (y) {closeWin();}}
				    		});
			    		} else {
			    			closeWin();
			    		}
					}
				} else if (btid=='btn_help') {//帮助
					openWindowByUrl(new Date().getTime()+"", flvar.url_help);
				} else if (btid=='btn_downpdf') {
                    fl_downloadpdf();
                }
		    });
		}
	};
	
	//显示按钮栏按钮
	window.showCanvasToolbarButtons = function() {
		if (!fl.tbcavans) return;
		flvar.layoutPattern=="LaneBased" && fl.tbcavans.showItem('sp0');
		//fl.tbcavans.showItem('sp1');
		fl.tbcavans.showItem('sp2');
		fl.tbcavans.showItem('sp3');
		fl.tbcavans.showItem('sp4');
		fl.tbcavans.showItem('btn_save');
		fl.tbcavans.showItem('btn_reset');
		fl.tbcavans.showItem('btn_downbpmn');
		fl.tbcavans.showItem('btn_downsvg');
		//fl.tbcavans.showItem('btn_vertical');
		//fl.tbcavans.showItem('btn_validate');
		fl.tbcavans.showItem('btn_showValidate');
		//fl.tbcavans.showItem('btn_theme');
		fl.tbcavans.showItem('btn_fs');
		fl.tbcavans.showItem('btn_fs1');
		fl.tbcavans.showItem('btn_resetscroll');
		//fl.tbcavans.hideItem('btn_dataflow');
	};
	
	window.callShowValidationInfo = function(callSave) {
		
		if (fl.curflow.otherConfig.validateFailed) {//验证失败直接返回
			return;
		}
		
		var dtd = $.Deferred();
		
		function showSave() {
			if (fl.curflow.otherConfig.validateErrors 
					&& fl.curflow.otherConfig.validateErrors.rows 
					&& fl.curflow.otherConfig.validateErrors.rows.length) {//如果有验证错误消息，弹出提示
				if (!callSave) {
					showValidationErrors(false);
				} else {
					if (fl_hasValidationErrors()) {
						showValidationErrors(false);//有错误总是不保存  
					} else {
						dhtmlx.message({
			                "type": "confirm-warning",
			                "title" : fmd_i18n_title_tip,
			    			"text": fmd_i18n_msg_hasValidateError,
			    			"ok" : fmd_i18n_b_yes,
			    			"cancel" : fmd_i18n_b_no,
			    			"callback" : function(y) {if (y) {saveFlow();}else{showValidationErrors(false);}}
			    		});
					} 
				}
			} else {//如果没有验证错误消息，直接检查是否需要保存
				msg(fmd_i18n_msg_noValidationError);
				if (callSave) {
					saveFlow();
				}
			}
			dtd.resolve();
		}
		
		setTimeout(showSave(), 1);
		return dtd.promise();
	}
	
	//纵向视图
	window.fl_showVertical = function() {
		openWindowByUrl(new Date().getTime()+"", ctxpath + "/flow/instanceDesign.action?layoutPattern=Vertical&flowid="+fl.curflow.id+"&piEid="+flvar.piEid);
	};
	
	window.getFlowData = function(callback) {
		doGetAsyncJson(flvar.url_piinfo + flvar.piEid + '?timezoneOffset='+new Date().getTimezoneOffset(),
			function(pi){
				if (pi) {
                    flvar.flowid = pi.bpdId;
                    flvar.versionid = pi.versionid;
                    getFlowDataByBpdIdVid(pi.bpdId, pi.versionid, callback);
				} else {
                    msgErr(fmd_i18n_msg_readfail);
				}
			},
			function () {
				msgErr(fmd_i18n_msg_readfail);
            });
	}
	
	//加载完成执行的方法
	window.fl_afterFlowLoaded = function() {
		fl.curflow.oldBpmnConfig = MyUtilJs.copyObj(fl.curflow.bpmnConfig);
		delete fl.curflow.oldBpmnConfig.processSettings;
		$.when(
        	id_getActivityState()
        ).done(function () {
            id_changeStyle();
            id_addTaskPic();
        });
	};
	
	//保存 
	//TODO 后台
	//暂停流程实例
	//部署
	//插入P_BPD_VERSION
	//更新activiti表L
	//恢复流程实例为活动
	window.saveFlow = function(callSave) {
		
		bi.saveDiagram(function(err, xml){
			unSelect();//取消选择
			//组装参数
			var param = {};
			param.bpdId = flvar.flowid;
			param.versionid = flvar.versionid;
			param.piEid = flvar.piEid;
			if (flvar.layoutPattern=="LaneBased") {
				param.bpmn = xml;
				bi.saveSVG(function(err, xml){
					param.svg = xml;
				});
				param.bpmnConfig = JSON.stringify(fl.curflow.bpmnConfig);
				param.otherConfig = JSON.stringify(fl.curflow.otherConfig);
				param.otherConfig.canvasheight = fl.canvasheight;
			} else {
				param.bpmn1 = xml;
				bi.saveSVG(function(err, xml){
					param.svg1 = xml;
				});
				param.bpmnConfig1 = JSON.stringify(fl.curflow.bpmnConfig);
				param.otherConfig1 = JSON.stringify(fl.curflow.otherConfig);
				param.otherConfig1.canvasheight = fl.canvasheight;
			}
			
			doPostAsyncJson(flvar.url_save + flvar.piEid,
				{"param" : JSON.stringify(param)},
				function(ret) {
                    if (!ret || !ret.result) {
                        msgErr(fmd_i18n_msg_commitfail);
                        fl.cell_designer.progressOff();
                    } else {
                        fl.unSavedChange = false;
                        fl.cell_designer.progressOff();
                        alertWarn(fmd_i18n_success, fmd_i18n_success, function(){
                            //如果是全屏，先关闭全屏
                            var el = $('#maindiv > .dhx_cell_layout:last')[0];
                            if (fullScreenApi.isFullScreen(el)) {
                                fullScreenApi.cancelFullScreen(el);
                            }
                            closeWin();
                        });
                    }
				},
				function () {
					msgErr(fmd_i18n_msg_commitfail);
				} );
		});
	};
	
	/*flfilters.images = {
		"imgfilterDone" : {
			"url" : ctxpath + ""
		}
	}*/
	fldmeta_prop.funcOnCompChanged.SequenceFlow = function(elemid, elem) {
		if(insd.seqflows && insd.seqflows[elemid]) {
			var sf = Snap("svg g[data-element-id='"+elemid+"'] .djs-visual path");
			if (sf) sf.attr({"stroke":"#58cc4e","style":'stroke-width: 2; stroke-linejoin: round; marker-end:url("#markerSequenceFlowEndRan")'});
		}
	};

}

//任务加图片
function id_addTaskPic() {
	var overlays = bi.renderer.get('overlays');
	for (var i in fl.curflow.oldBpmnConfig) {
		if (i.indexOf('Task_')<0 && !i.startsWith('SubProcess_')) {
			continue;
		}
		var state = id_getState(i);
		if (state=='new' || state=='pending') {
			continue;
		}
		var img = flvar.iconpath_flowcanvas+'task'+state+'.png';
		var elem = getIORegistedElem(i);//获取bpmn元素
		if (!elem) {
			//console.log("Did not find id==="+i);
			continue;
		}
		overlays.add(elem, 'note', {//增加图片
	        position: {left: 0, top: 0},
	        html: '<div><img src="'+img+'"/></div>'
	    });
	}
}

//
function id_changeStyle(){
	var svg = Snap("svg");
	//根据线标记已走过线和环节 
	var markerCloned = false;
	for (var i in insd.seqflows) {
		if (!insd.seqflows[i].sequenceFlow || svg.select("g[data-element-id='"+insd.seqflows[i].sequenceFlow+"']")==null) {
			continue;	//驳回的线无 sequenceFlow id 或不是当前流程图的
		}
		//标记任务和网关
		var graph = "rect";
		if (insd.seqflows[i].sourceActivityId.indexOf("StartEvent_")>=0) {
			graph = "circle";
		} else if (insd.seqflows[i].sourceActivityId.indexOf("Gateway_")>=0) {
			graph = "polygon";
		}
		svg.select("g[data-element-id='"+insd.seqflows[i].sourceActivityId+"'] .djs-visual "+
				graph).attr({"stroke":"#1ddb1d","strokeWidth":1,"filter":"none"});
		//标记线
		var sf = svg.select("g[data-element-id='"+insd.seqflows[i].sequenceFlow+"'] .djs-visual path").attr({"stroke":"#58cc4e"});
		if (!markerCloned) {
			var markerId = sf.node.style.markerEnd.replace(/"/g,'');
			markerId = markerId.substr(5, markerId.length-6);
			//new marker
			svg.select("defs").append(svg.select("marker[id='"+markerId+"']").clone().attr({"id":"markerSequenceFlowEndRan"}));
			svg.select("marker[id='markerSequenceFlowEndRan']").select("path").attr({"fill":"#58cc4e"});
			markerCloned = true;
		}
		//set to new marker
		//sf.attr({'markerEnd':'url("#markerSequenceFlowEndRan")'});
		sf.attr({"style":'stroke-width: 2; stroke-linejoin: round; marker-end:url("#markerSequenceFlowEndRan")'});
	}
	//标记正在处理中
	/*for (var i in fl.curflow.oldBpmnConfig) {
		var state = id_getState(i);
		if (state!='todo') {
			continue;
		}
		if (i.indexOf('Task_')>=0 || i.startsWith('SubProcess_')) {
			var curTask = svg.select("g[data-element-id='"+i+"']");
			if (!curTask) continue;
			curTask.select(".djs-visual rect").attr("filter","url(#svgFilterBlur)")
					.attr({"strokeWidth":3, "stroke":"#ff7f00"})
		}
	}*/
}

//判断任务状态
//new - 在设计器新增加, todo - 待办, done - 已办, pending - 未运行
function id_getState(activityId) {
    if (!fl.curflow.oldBpmnConfig[activityId]) return "new";
	if (activityId.startsWith('UserTask_')) {//人工任务
		if (insd.todos[activityId]) return "todo";
		if (insd.dones && insd.dones[activityId]) return "done";
	} else {
		if (insd.activitieStates[activityId]) return insd.activitieStates[activityId];
	}
	return "pending";
}

function id_getActivityState(){
	//get seqflows info
    return doGetAsyncJson(flvar.url_get_infoforchange + flvar.piEid + '?timezoneOffset='+new Date().getTimezoneOffset(),
        function(ret) {

    		//待办
            //console.log(ret);
            if (!ret) {msgErr(fmd_i18n_msg_readfail);return;}
            insd.todos = ret.todos;

            //已办
            insd.dones = ret.dones;

			//连接线
            //console.log(ret);
            insd.seqflows = ret.seqflows;
            //选中当前子流程
            var targetMap = {};//目标
            var sourceMap = {};//记录来源

            var seqflows = {};
            for (var i in insd.seqflows) {
                seqflows[insd.seqflows[i].sequenceFlow] = insd.seqflows[i];
                targetMap[insd.seqflows[i].sourceActivityId] = insd.seqflows[i].sequenceFlow;
                sourceMap[insd.seqflows[i].targetActivityId] = insd.seqflows[i].sequenceFlow;
            }
            insd.seqflows = seqflows;

            insd.activitieStates = {};
            for (var i in fl.curflow.oldBpmnConfig) {
                if (targetMap[i]) {//跑过的
                    insd.activitieStates[i] = 'done';
                } else if (sourceMap[i]) {//正在跑的
                    insd.activitieStates[i] = 'todo';
                } else {
                    insd.activitieStates[i] = 'pending';
                }
            }
            //console.log('activitieStates=='+insd.activitieStates);
        },
        function () { msgErr(fmd_i18n_msg_readfail);}
    );
}


